﻿using SocialCee.ExternalSystems.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Text;

namespace SocialCee.ExternalSystems.Loader
{
    /// <summary>
    /// Loads external DLLs
    /// </summary>
    public class ContainerLoad
    {
        private CompositionContainer _container;

        [Import(typeof(IExternalSystemsFactory))]
        public IExternalSystemsFactory SocialMediaClients;

        /// <summary>
        /// Load assemblies
        /// </summary>
        /// <param name="ExtensionsPath"></param>
        public ContainerLoad(string ExtensionsPath)
        {
            var catalog = new AggregateCatalog();
            //Adds all the parts found in the same assembly as the Program class
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(ContainerLoad).Assembly));
            catalog.Catalogs.Add(new DirectoryCatalog(ExtensionsPath));


            //Create the CompositionContainer with the parts in the catalog
            _container = new CompositionContainer(catalog);

            //Fill the imports of this object
            try
            {
                this._container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }
        }

        /// <summary>
        /// If read was completed and there was any client
        /// </summary>
        public bool WasInit
        {
            get
            {
                return SocialMediaClients != null && SocialMediaClients.GetClientNames().Count > 0;
            }
        }

        /// <summary>
        /// Gets clients by with its name
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, IClient> GetClients()
        {
            if (WasInit)
                return SocialMediaClients.GetClients();

            return null;
        }

        /// <summary>
        /// Get all clients names
        /// </summary>
        /// <returns></returns>
        public List<string> GetClientNames()
        {
            if (WasInit)
                return SocialMediaClients.GetClientNames();

            return null;
        }
    }
}
